package com.edu.hre.struts.action.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.util.MessageResources; 

import com.edu.hre.common.encrypt.Encrypter;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.db.pojo.HreEmployee;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.login.LoginForm;

public class LoginAction extends Action {
	private static final Logger logger = Logger.getLogger(LoginAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private final String ACTION_NAME = "login";

	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		LoginForm loginForm = (LoginForm) form;
		if(RequestUtils.isLogout(request)){
			request.getSession().invalidate();
			return mapping.findForward(ACTION_NAME);
		}
		ActionErrors errors = validateLogin(request, loginForm.getUsername(), loginForm.getPassword());
		if (errors != null && !errors.isEmpty()) {
			saveErrors(request, errors);
			return mapping.findForward(ACTION_NAME);
		} 
		HreUser user = baseService.getFirstPojoAnd(new String[] { "userName", "userPassword", "status", "deleted"},
				new int[] {Compare.EQUAL, Compare.EQUAL, Compare.EQUAL, Compare.EQUAL }, 
				new Object[] { loginForm.getUsername(), Encrypter.encodeMD5(loginForm.getPassword()), true, false}, null, null, 0, HreUser.class);
		if (user == null) {
			errors.add("error", new ActionMessage("label.authen.failure"));
			saveErrors(request, errors);
			return mapping.findForward(ACTION_NAME);
		}
		if (user.getEmpNumber() != null) {
			HreEmployee employee = baseService.getFirstPojo("empNumber", Compare.EQUAL, user.getEmpNumber(), null, null, 0, HreEmployee.class);
			if(employee != null){
				request.getSession().setAttribute(RequestUtils.Attribute.EMPLOYEE_INFO, employee);
			} else {
				errors.add("error", new ActionMessage("label.authen.failure"));
				saveErrors(request, errors);
				return mapping.findForward(ACTION_NAME);
			}
		}
		request.getSession().setAttribute(RequestUtils.Attribute.USER_INFO, user);
		String urlBeforeLogin = (String)request.getSession().getAttribute(RequestUtils.Attribute.URL_BEFORE_LOGIN);
		if(StringUtils.isNotBlank(urlBeforeLogin)){
			request.getSession().removeAttribute(RequestUtils.Attribute.URL_BEFORE_LOGIN);
			response.sendRedirect(urlBeforeLogin);
			return null;
		}
		return new ActionForward("/empPersonalDetailUpdate.do?id=" + user.getEmpNumber(), true);
	}

	public ActionErrors validateLogin(HttpServletRequest request, String username, String password) {
		ActionErrors errors = new ActionErrors();
		try {
			MessageResources messages = getResources(request);
			if (username == null || username.length() < 1) {
				errors.add("error", new ActionMessage("errors.required", messages.getMessage(getLocale(request), "label.username")));
			} else if (password == null || password.length() < 1) {
				errors.add("error", new ActionMessage("errors.required", messages.getMessage(getLocale(request), "label.password")));
			}
		} catch (Exception e) {
			logger.error("LoginAction - validateLogin() = " + e);
		}
		return errors;
	}
}
